/**
 * 数据加载器 - 提供图数据的加载、验证和处理功能
 */
import { sailisiGraphData } from './sailisiSampleData.js'

/**
 * 从JSON文件加载图数据
 * @param {string} jsonPath - JSON文件路径
 * @returns {Promise<Object>} 图数据对象
 */
export async function loadGraphDataFromJSON(jsonPath) {
  try {
    console.log(`[loadGraphDataFromJSON] 开始加载: ${jsonPath}`)
    
    const response = await fetch(jsonPath)
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    console.log(`[loadGraphDataFromJSON] 数据加载成功，节点数: ${Object.keys(data.nodes || {}).length}`)
    
    return data
  } catch (error) {
    console.error(`[loadGraphDataFromJSON] 加载失败:`, error)
    throw error
  }
}

/**
 * 获取默认图数据
 * @returns {Object} 默认图数据
 */
export function getDefaultGraphData() {
  console.log('[getDefaultGraphData] 返回默认数据')
  return sailisiGraphData
}

/**
 * 验证图数据格式
 * @param {Object} data - 要验证的数据
 * @returns {Object} 验证结果
 */
export function validateGraphData(data) {
  const result = {
    valid: true,
    errors: [],
    warnings: []
  }
  
  // 检查基本结构
  if (!data || typeof data !== 'object') {
    result.valid = false
    result.errors.push('数据不是有效的对象')
    return result
  }
  
  // 检查节点数据
  if (!data.nodes || typeof data.nodes !== 'object') {
    result.valid = false
    result.errors.push('缺少节点数据')
  } else {
    const nodeCount = Object.keys(data.nodes).length
    if (nodeCount === 0) {
      result.warnings.push('节点数据为空')
    } else {
      console.log(`[validateGraphData] 节点数量: ${nodeCount}`)
    }
  }
  
  // 检查边数据
  if (!data.edges || typeof data.edges !== 'object') {
    result.valid = false
    result.errors.push('缺少边数据')
  } else {
    const edgeCount = Object.keys(data.edges).length
    if (edgeCount === 0) {
      result.warnings.push('边数据为空')
    } else {
      console.log(`[validateGraphData] 边组数量: ${edgeCount}`)
    }
  }
  
  // 检查设置
  if (!data.settings) {
    result.warnings.push('缺少设置信息，将使用默认设置')
  }
  
  console.log(`[validateGraphData] 验证完成，有效: ${result.valid}`)
  return result
}

/**
 * 获取图数据统计信息
 * @param {Object} data - 图数据
 * @returns {Object} 统计信息
 */
export function getGraphStatistics(data) {
  if (!data) {
    return {
      nodeCount: 0,
      edgeCount: 0,
      totalDataPoints: 0,
      nodeTypes: {},
      edgeTypes: {}
    }
  }
  
  // 统计节点
  const nodeCount = Object.keys(data.nodes || {}).length
  const nodeTypes = {}
  
  Object.values(data.nodes || {}).forEach(node => {
    const type = node.type || 'default'
    nodeTypes[type] = (nodeTypes[type] || 0) + 1
  })
  
  // 统计边
  let edgeCount = 0
  const edgeTypes = {}
  
  Object.values(data.edges || {}).forEach(edgeGroup => {
    if (edgeGroup.data && Array.isArray(edgeGroup.data)) {
      edgeCount += edgeGroup.data.length
      edgeGroup.data.forEach(edge => {
        const type = edge.type || 'default'
        edgeTypes[type] = (edgeTypes[type] || 0) + 1
      })
    }
  })
  
  const totalDataPoints = nodeCount + edgeCount
  
  const stats = {
    nodeCount,
    edgeCount,
    totalDataPoints,
    nodeTypes,
    edgeTypes
  }
  
  console.log('[getGraphStatistics] 统计信息:', stats)
  return stats
}

/**
 * 转换数据格式为Graph类需要的格式
 * @param {Object} rawData - 原始数据
 * @returns {Object} 转换后的数据
 */
export function transformGraphData(rawData) {
  if (!rawData) {
    return getDefaultGraphData()
  }
  
  const transformedData = {
    nodes: {},
    edges: {},
    settings: rawData.settings || {
      epoch: 'time',
      epochFormat: 'YYYY-M-D H:m:s',
      source: 'source',
      target: 'target'
    }
  }
  
  // 转换节点数据
  if (rawData.nodes) {
    Object.entries(rawData.nodes).forEach(([name, nodeData]) => {
      transformedData.nodes[name] = {
        id: name,
        name: name,
        type: nodeData.type || 'default',
        category: nodeData.category || 'default',
        group: nodeData.group || 1,
        data: [nodeData]
      }
    })
  }
  
  // 转换边数据
  if (rawData.edges) {
    Object.entries(rawData.edges).forEach(([groupName, edgeGroup]) => {
      if (edgeGroup.data && Array.isArray(edgeGroup.data)) {
        edgeGroup.data.forEach((edge, index) => {
          const edgeId = `${groupName}_${index}`
          transformedData.edges[edgeId] = {
            id: edgeId,
            source: edge.source,
            target: edge.target,
            type: edge.type || 'default',
            weight: edge.weight || 1,
            time: edge.time || new Date().toISOString(),
            data: [edge]
          }
        })
      }
    })
  }
  
  console.log('[transformGraphData] 数据转换完成')
  return transformedData
}

/**
 * 合并多个数据源
 * @param {...Object} dataSources - 数据源数组
 * @returns {Object} 合并后的数据
 */
export function mergeGraphData(...dataSources) {
  const mergedData = {
    nodes: {},
    edges: {},
    settings: {}
  }
  
  dataSources.forEach((data, index) => {
    if (!data) return
    
    // 合并节点
    if (data.nodes) {
      Object.assign(mergedData.nodes, data.nodes)
    }
    
    // 合并边
    if (data.edges) {
      Object.assign(mergedData.edges, data.edges)
    }
    
    // 合并设置（最后一个有效设置优先）
    if (data.settings) {
      Object.assign(mergedData.settings, data.settings)
    }
  })
  
  console.log(`[mergeGraphData] 合并了 ${dataSources.length} 个数据源`)
  return mergedData
}

/**
 * 过滤图数据
 * @param {Object} data - 原始数据
 * @param {Object} filters - 过滤条件
 * @returns {Object} 过滤后的数据
 */
export function filterGraphData(data, filters = {}) {
  if (!data) return getDefaultGraphData()
  
  const filteredData = {
    nodes: {},
    edges: {},
    settings: data.settings || {}
  }
  
  // 过滤节点
  if (data.nodes) {
    Object.entries(data.nodes).forEach(([name, nodeData]) => {
      let include = true
      
      // 按类型过滤
      if (filters.nodeTypes && filters.nodeTypes.length > 0) {
        include = include && filters.nodeTypes.includes(nodeData.type)
      }
      
      // 按组过滤
      if (filters.groups && filters.groups.length > 0) {
        include = include && filters.groups.includes(nodeData.group)
      }
      
      // 按类别过滤
      if (filters.categories && filters.categories.length > 0) {
        include = include && filters.categories.includes(nodeData.category)
      }
      
      if (include) {
        filteredData.nodes[name] = nodeData
      }
    })
  }
  
  // 过滤边
  if (data.edges) {
    Object.entries(data.edges).forEach(([groupName, edgeGroup]) => {
      if (edgeGroup.data && Array.isArray(edgeGroup.data)) {
        const filteredEdges = edgeGroup.data.filter(edge => {
          let include = true
          
          // 按类型过滤
          if (filters.edgeTypes && filters.edgeTypes.length > 0) {
            include = include && filters.edgeTypes.includes(edge.type)
          }
          
          // 按权重过滤
          if (filters.minWeight !== undefined) {
            include = include && (edge.weight || 0) >= filters.minWeight
          }
          
          if (filters.maxWeight !== undefined) {
            include = include && (edge.weight || 0) <= filters.maxWeight
          }
          
          return include
        })
        
        if (filteredEdges.length > 0) {
          filteredData.edges[groupName] = {
            data: filteredEdges
          }
        }
      }
    })
  }
  
  console.log('[filterGraphData] 数据过滤完成')
  return filteredData
}